package threadTea;


/**
 * 测试多线程并发安全问题
 * 当多个线程并发操作同一临界资源，由于线程切换实际不确定，导致操作顺序出现混乱而从引发不良后果。
 * 临界资源:操作该资源的完整过程同一时间只能被单个线程进行
 */
public class BankTest02 {
    private static boolean success1 = false;
    private static boolean success2 = false;
    public static void main(String[] args) {
        Bank02 bank = new Bank02();
        int num = 1;
        while(true) {
            Thread t1 = new Thread("张百万") {
                public void run() {
                    success1 = bank.getMoney(20000);
                }
            };
            Thread t2 = new Thread("李富贵") {
                public void run() {
                    success2 = bank.getMoney(20000);
                }
            };
            t1.start();
            t2.start();

            //让主线程阻塞，目的是等待t1,t2执行完毕
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (success1 && success2) {
                System.out.println("全部取款成功，出现了并发安全问题!");
                System.out.println("共测试了:"+num+"次");
                System.out.println("余额："+bank.getAccount());
                break;
            } else {
                num++;
                bank.saveAccount(20000);
                success1=false;
                success2=false;
            }
        }
    }
}
